<?php
/**
 * OrderController.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-05-23 10:45:26
 * @modified   2023-05-23 10:45:26
 */

namespace Beike\Seller\Http\Controllers;

use Beike\Admin\Http\Resources\OrderSimple;
use Beike\Models\OrderShipment;
use Beike\Seller\Repositories\OrderRepo;
use Beike\Services\ShipmentService;
use Beike\Services\StateMachineService;
use Beike\Shop\Http\Resources\Account\OrderShippingList;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    /**
     * 获取订单列表
     *
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function index(Request $request)
    {
        $orders = OrderRepo::filterOrders($request->all());
        if (class_basename("\Beike\Shop\Http\Resources\Account\OrderSimpleList")) {
            $orders = \Beike\Shop\Http\Resources\Account\OrderSimpleList::collection($orders);
        } elseif (class_exists("\Beike\Shop\Http\Resources\Account\OrderList")) {
            $orders = \Beike\Shop\Http\Resources\Account\OrderList::collection($orders);
        } else {
            throw new \Exception('Class not exists');
        }
        $data   = [
            'orders'   => $orders,
            'statuses' => StateMachineService::getAllStatuses(),
        ];

        return view('seller::pages.orders.index', $data);
    }

    /**
     * 导出订单列表
     *
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function export(Request $request)
    {
        try {
            $orders = OrderRepo::filterAll($request->all());
            $items  = OrderSimple::collection($orders)->jsonSerialize();

            return $this->downloadCsv('orders', $items, 'order');
        } catch (\Exception $e) {
            return redirect(admin_route('orders.index'))->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 查看单个订单
     *
     * @param Request $request
     * @param int     $id
     * @return mixed
     * @throws \Exception
     */
    public function show(Request $request, int $id)
    {
        $order = \Beike\Seller\Models\Order::findOrFail($id);
        $order->load(['orderTotals', 'orderHistories', 'orderShipments']);
        $data = [
            'order'      => $order,
            'html_items' => [],
            'statuses'   => StateMachineService::getInstance($order)->nextBackendStatuses(),
        ];

        return view('seller::pages.orders.form', $data);
    }

    /**
     * 更新订单状态,添加订单更新日志
     *
     * @param Request $request
     * @param int     $id
     * @return array
     * @throws \Throwable
     */
    public function updateStatus(Request $request, int $id)
    {
        $order   = \Beike\Seller\Models\Order::findOrFail($id);
        $status  = $request->get('status');
        $comment = $request->get('comment');
        $notify  = $request->get('notify');

        $shipment = ShipmentService::handleShipment(\request('express_code'), \request('express_number'));

        $stateMachine = new StateMachineService($order);
        $stateMachine->setShipment($shipment)->changeStatus($status, $comment, $notify);

        return json_success(trans('common.updated_success'));
    }

    /**
     * 更新发货信息
     * @param Request $request
     * @param int     $id
     * @param int     $orderShipmentId
     * @return JsonResponse
     * @throws \Throwable
     */
    public function updateShipment(Request $request, int $id, int $orderShipmentId)
    {
        $data          = $request->all();
        $orderShipment = OrderShipment::query()->where('order_id', $id)->findOrFail($orderShipmentId);
        ShipmentService::updateShipment($orderShipment, $data);

        return json_success(trans('common.updated_success'));
    }

    public function createShipment(Request $request, int $id)
    {
        $shipment = ShipmentService::handleShipment(\request('express_code'), \request('express_number'));
        ShipmentService::addShipment($id, $shipment);

        return json_success(trans('common.created_success'));
    }

    public function shipping(Request $request)
    {
        $orderIds = $request->get('selected', '');
        $orderId  = $request->get('order_id');
        if (! $orderIds && $orderId) {
            $orderIds = $orderId;
        }
        $orderIds = explode(',', $orderIds);
        $orders   = OrderRepo::filterAll(['order_ids' => $orderIds]);

        $data = [
            'orders' => OrderShippingList::collection($orders)->jsonSerialize(),
        ];

        $data = hook_filter('admin.order.shipping.data', $data);

        return view('admin::pages.orders.shipping', $data);
    }
}
